<template>
  <el-select
    class="le-select"
    :placeholder="placeholder"
    :multiple="field.multiple"
    :disabled="disabled"
    :value="secureValue"
    @visible-change="visibleChange"
    @input="change">
    <el-option
      v-for="option in options"
      :key="option.id"
      :label="option.label"
      :value="option.value">
    </el-option>
  </el-select>
</template>


<script>
  import { Select, Option } from 'element-ui'

  export default {
    name: 'le-select',
    components: {
      'el-select': Select,
      'el-option': Option,
    },
    props: {
      value: {
        required: true,
      },
      field: {
        type: Object,
        required: true,
      },
      record: {
        type: Object,
        required: true,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      placeholder: {
        type: String,
      },
    },
    data() {
      return {
        options: [],
      }
    },
    computed: {
      dictCode() {
        return this.$dictCode
      },
      secureValue() {
        if (this.field.multiple && !this.value) {
          return []
        }
        return this.value
      },
      relyData() {
        if (this.field.rely) {
          return this.record[this.field.rely]
        }
      },
    },
    watch: {
      // 监听 select 所依赖的字段的值的变化
      relyData(newValue, oldValue) {
        // 依赖值变化(由非 undefined 变为另一个值)的时候，清空 select 绑定的值
        if (oldValue !== undefined) {
          this.$emit('input', undefined)
        }
        this.$httpGet(`${this.field.url}?${this.field.rely}=${this.relyData}`).then((response) => {
          this.options = response.data
        })
      },
    },
    methods: {
      loadData() {
        if (!this.field.url) {
          this.options = this.dictCode[this.field.key] || []
          return
        }
        if (this.field.rely) {
          return
        }
        this.$httpGet(this.field.url).then((response) => {
          this.options = response.data
        })
      },
      // 当 select 选中值变化时，触发父组件的 v-model 绑定
      change(value) {
        this.$emit('input', value)
      },
      // 下拉框出现时, 并且当前下拉框的依赖字段为空时触发
      visibleChange(visible) {
        if (visible && this.field.rely && !this.relyData) {
          this.$message.error(`请先选择${this.field.relyName}！`)
        }
      },
    },
    created() {
      this.loadData()
    },
  }
</script>


<style lang="scss">
  .le-select {
    width: 100%;
  }
</style>
